package kyssion.leetcode.num51_100;

import kyssion.leetcode.util.ListNode;


public class code92_反转列表2 {

    public static void main(String[] args) {
        ListNode lite = ListNode.createListNode(new int[]{
                1,2,3,4,5
        });
        lite = new code92_反转列表2().reverseBetween(lite,1,5);
        ListNode.showListNode(lite);
    }

    public ListNode reverseBetween(ListNode head, int m, int n) {
        m = m == 0 ? 1 : m;
        int speed = 1;
        ListNode sBefore = new ListNode(-1);
        ListNode start = head;
        sBefore.next = head;
        head = sBefore;
        // m == 1
        while (speed < m && start != null) {
            sBefore = sBefore.next;
            start = start.next;
            speed++;
        }
        //sBefore - start -
        if (start == null || start.next == null) {
            return head.next;
        }
        ListNode exChange = start.next;
        int length = n - m;
        speed = 1;
        start.next = null;
        while (exChange != null && speed <= length) {
            ListNode next = exChange.next;
            exChange.next = start;
            start = exChange;
            exChange = next;
            speed++;
        }
        sBefore.next.next = exChange;
        sBefore.next = start;
        return head.next;
    }
}
